using System.Windows.Forms;
using ShadeTree.Binding.Validation;

namespace ShadeTree.Binding
{
    public class ValidationMonitor : IValidationMonitor
    {
        private IScreenBinder _binder;
        private ErrorProvider _errorProvider;

        public ValidationMonitor(ErrorProvider errorProvider)
        {
            _errorProvider = errorProvider;
        }

        #region Implementation of IValidationMonitor

        public IScreenBinder Binder
        {
            set { _binder = value; }
        }

        public void ClearErrors()
        {
            _errorProvider.Clear();
        }

        public void ShowErrorMessages(Notification notification)
        {
            //ClearErrors();

            foreach (NotificationMessage message in notification.AllMessages)
            {
                _errorProvider.SetError(_binder.FindElementByField(message.FieldName).Control as Control, message.Message);
                //ValidateField(_binder.FindElementByField(message.FieldName), message.Message);
            }
        }

        public void ValidateField(IBoundScreenElement element, object model)
        {
            var messages = Validator.ValidateField(model, element.FieldName);

            if(messages.Length > 0)
                _errorProvider.SetError(_binder.FindElementByField(element.FieldName).Control as Control, model.ToString() );
            else
            {
                
                _errorProvider.SetError(_binder.FindElementByField(element.FieldName).Control as Control, string.Empty);
            }
            
        }

        #endregion
    }
}